All files / src/app/api/products/[id]/reviews route.ts

98.52% Statements 268/272
85.71% Branches 36/42
100% Functions 2/2
98.52% Lines 268/272

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 2731x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x     9x 9x 9x 9x 9x 1x 1x 8x 8x 8x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 9x 1x 1x 9x 1x 1x 1x 9x 9x 4x 9x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 6x 6x 6x 6x 6x 6x 6x 6x 6x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 6x 6x 6x 9x 1x 1x 6x 6x 6x 6x 6x 9x 9x 9x 9x 30x 30x 30x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x     10x 10x 10x 10x 10x 1x 1x 9x 9x 9x 9x 9x 10x 1x 1x 8x 8x 8x 8x 8x 10x 1x 1x 7x 7x 7x 7x 7x 7x 7x 10x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x  
export const dynamic = "force-dynamic";
 
import { NextRequest, NextResponse } from 'next/server';
import { prisma } from "@/lib/prisma";
import { z } from "zod";
import {
  withErrorHandling,
  withAuth,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { Session } from "next-auth";
import { RouteContext } from "@/lib/api/middleware";
 
/**
 * Query schema for GET requests
 */
const querySchema = z.object({
  page: z.coerce.number().int().positive().default(1),
  limit: z.coerce.number().int().min(1).max(50).default(10),
  sortBy: z.enum(["recent", "helpful", "rating_high", "rating_low"]).default("recent"),
  rating: z.coerce.number().int().min(1).max(5).optional()});
 
/**
 * Create review schema for POST requests
 */
const createReviewSchema = z.object({
  rating: z.number().int().min(1).max(5),
  comment: z.string().min(10).max(2000).optional()});
 
interface ReviewData {
  reviews: Array<{
    id: number;
    rating: number;
    comment: string | null;
    createdAt: Date;
    updatedAt: Date;
    user: {
      id: number;
      name: string | null;
      image: string | null;
    };
    helpfulCount: number;
    notHelpfulCount: number;
  }>;
  stats: {
    averageRating: number;
    totalReviews: number;
    distribution: Record<number, number>;
  };
  pagination: {
    page: number;
    limit: number;
    total: number;
    pages: number;
  };
}
 
/**
 * GET /api/products/[id]/reviews
 * Get reviews for a specific product with stats
 */
async function handleGet(
  request: NextRequest,
  context?: RouteContext
): Promise<NextResponse<ApiSuccessResponse<ReviewData>>> {
  if (!context?.params) {
    throw ApiError.invalidId("product");
  }
 
  const resolvedParams = await context.params;
  const productId = parseInt(resolvedParams.id);
 
  if (isNaN(productId)) {
    throw ApiError.invalidId("product");
  }
 
  const searchParams = request.nextUrl.searchParams;
  const query = querySchema.parse({
    page: searchParams.get("page") || 1,
    limit: searchParams.get("limit") || 10,
    sortBy: searchParams.get("sortBy") || "recent",
    rating: searchParams.get("rating") || undefined});
 
  const skip = (query.page - 1) * query.limit;
 
  // Build where clause
  const where = {
    productId,
    ...(query.rating ? { rating: query.rating } : {})};
 
  // Build sort order
  let orderBy: Record<string, string> = { createdAt: "desc" };
  switch (query.sortBy) {
    case "rating_high":
      orderBy = { rating: "desc" };
      break;
    case "rating_low":
      orderBy = { rating: "asc" };
      break;
    case "helpful":
      // Sort by helpful count - we'll handle this with raw query or separate logic
      orderBy = { createdAt: "desc" };
      break;
    case "recent":
    default:
      orderBy = { createdAt: "desc" };
  }
 
  // Fetch reviews, total count, and stats in parallel
  const [reviews, total, stats] = await Promise.all([
    prisma.review.findMany({
      where,
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true}},
        helpful: {
          select: {
            helpful: true}}},
      orderBy,
      skip,
      take: query.limit}),
    prisma.review.count({ where }),
    prisma.review.aggregate({
      where: { productId },
      _avg: { rating: true },
      _count: { rating: true }}),
  ]);
 
  // Calculate rating distribution
  const distribution = await prisma.review.groupBy({
    by: ["rating"],
    where: { productId },
    _count: true});
 
  // Transform reviews with helpful counts
  const transformedReviews = reviews.map((review) => {
    const helpfulCount = review.helpful.filter((h) => h.helpful).length;
    const notHelpfulCount = review.helpful.filter((h) => !h.helpful).length;
 
    return {
      id: review.id,
      rating: review.rating,
      comment: review.comment,
      createdAt: review.createdAt,
      updatedAt: review.updatedAt,
      user: {
        id: review.user.id,
        name: review.user.name,
        image: review.user.image},
      helpfulCount,
      notHelpfulCount};
  });
 
  // Sort by helpful if requested (after transformation)
  if (query.sortBy === "helpful") {
    transformedReviews.sort((a, b) => b.helpfulCount - a.helpfulCount);
  }
 
  return successResponse(
    {
      reviews: transformedReviews,
      stats: {
        averageRating: stats._avg.rating || 0,
        totalReviews: stats._count.rating,
        distribution: Object.fromEntries(
          [1, 2, 3, 4, 5].map((rating) => [
            rating,
            distribution.find((d) => d.rating === rating)?._count || 0,
          ])
        )},
      pagination: {
        page: query.page,
        limit: query.limit,
        total,
        pages: Math.ceil(total / query.limit)}},
    {
      headers: {
        "Cache-Control": "public, s-maxage=60, stale-while-revalidate=120"}}
  );
}
 
export const GET = withErrorHandling(handleGet);
 
/**
 * POST /api/products/[id]/reviews
 * Submit a review for a product (authenticated users only)
 */
async function handlePost(
  request: NextRequest,
  context: RouteContext | undefined,
  session: Session
): Promise<NextResponse<ApiSuccessResponse<{
  id: number;
  rating: number;
  comment: string | null;
  createdAt: Date;
  user: {
    id: number;
    name: string | null;
    image: string | null;
  };
  message: string;
}> | ApiErrorResponse>> {
  if (!context?.params) {
    throw ApiError.invalidId("product");
  }
 
  const resolvedParams = await context.params;
  const productId = parseInt(resolvedParams.id);
 
  if (isNaN(productId)) {
    throw ApiError.invalidId("product");
  }
 
  // Get user from session
  const user = await prisma.user.findUnique({
    where: { email: session.user.email! }});
 
  if (!user) {
    throw ApiError.notFound("User");
  }
 
  // Check if product exists
  const product = await prisma.product.findUnique({
    where: { id: productId }});
 
  if (!product) {
    throw ApiError.notFound("Product", productId);
  }
 
  // Check if user already reviewed this product
  const existingReview = await prisma.review.findFirst({
    where: {
      productId,
      userId: user.id}});
 
  if (existingReview) {
    throw ApiError.conflict("You have already reviewed this product");
  }
 
  const body = await request.json();
  const validatedData = createReviewSchema.parse(body);
 
  const review = await prisma.review.create({
    data: {
      productId,
      userId: user.id,
      rating: validatedData.rating,
      comment: validatedData.comment},
    include: {
      user: {
        select: {
          id: true,
          name: true,
          image: true}}}});
 
  return createdResponse({
    id: review.id,
    rating: review.rating,
    comment: review.comment,
    createdAt: review.createdAt,
    user: review.user,
    message: "Review submitted successfully"});
}
 
export const POST = withErrorHandling(withAuth(handlePost));